package com.acceptable.qucun.generic.util;

import org.springframework.data.convert.Jsr310Converters;
import org.springframework.lang.NonNull;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

public class TimeUtil {
    public static LocalDateTime date2LocalDateTime(@NonNull Date date){
        return LocalDateTime.of(date.getYear() + 1900, date.getMonth() + 1,
                date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
//        return Jsr310Converters.DateToLocalDateTimeConverter.INSTANCE.convert(date);
    }

    public static Date localDateTime2Date(@NonNull LocalDateTime dateTime){
        return Jsr310Converters.LocalDateTimeToDateConverter.INSTANCE.convert(dateTime);
    }

    public static Date string2Date(@NonNull String str){
        Date date = null;
        if (StringFormatUtil.isEmpty(str))
            return null;
        if (str.contains("T"))
            str = str.replace("T", " ");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    // 有问题
    public static String mill2DayNumber(@NonNull long mill){
        StringBuilder res = new StringBuilder();
        int[] rate = new int[]{1000, 60, 60, 24};
        int[] num = new int[5];
        String[] unit = new String[]{"毫秒", "秒", "分钟", "小时", "天"};

        for (int i = 0; i < rate.length; i++){
            num[i] = (int) (mill % rate[i]);
            mill /= rate[i];
        }

        num[num.length - 1] = (int) (mill);

        for (int i = num.length - 1; i >= 0; i--){
            res.append(num[i]).append(unit[i]);
        }
        return res.toString();
    }
}
